/*
 * Created on 2005-8-13
 *
 */
package com.yl.cap.analyst.report.helper;

//Java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

//SAX
import org.xml.sax.InputSource;

//Avalon
import org.apache.avalon.framework.ExceptionUtil;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.logger.ConsoleLogger;

//FOP
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.apps.Options;
/**
* This class demonstrates the conversion of an FO file to PDF using FOP.
*/
public class FO2PDF {

  public void convertFO2PDF(File configFile,File fo, File pdf) throws IOException, FOPException {
      
      //Construct driver
      Driver driver = new Driver();
      
      //setup config
      Options o = new Options(configFile);
      
      //Setup logger
      Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
      driver.setLogger(logger);
      MessageHandler.setScreenLogger(logger);

      //Setup Renderer (output format)        
      driver.setRenderer(Driver.RENDER_PDF);
      
      //Setup output
      OutputStream out = new java.io.FileOutputStream(pdf);
      try {
          driver.setOutputStream(out);

          //Setup input
          InputStream in = new java.io.FileInputStream(fo);
          try {
              driver.setInputSource(new InputSource(in));
          
              //Process FO
              driver.run();
          } finally {
              in.close();
          }
      } finally {
          out.close();
      }
  }


  public static void main(String[] args) {
      try {
          System.out.println("FOP ExampleFO2PDF\n");
          System.out.println("Preparing...");
          
          //Setup directories
          File baseDir = new File("d:\\");
          File outDir = new File(baseDir, "out");
          outDir.mkdirs();

          //Setup input and output files            
          File fofile = new File(baseDir, "\\view\\fo\\20040110010\\r_20040110010401.fo");
          File pdffile = new File(outDir, "ResultFO2PDF.pdf");
          File conffile = new File(baseDir, "commonlib\\fop-0.20.5-src\\fop-0.20.5\\conf\\userconfig.xml");

          System.out.println("Input: XSL-FO (" + fofile + ")");
          System.out.println("Output: PDF (" + pdffile + ")");
          System.out.println();
          System.out.println("Transforming...");
          
          FO2PDF app = new FO2PDF();
          app.convertFO2PDF(conffile,fofile, pdffile);
          
          System.out.println("Success!");
      } catch (Exception e) {
          System.err.println(ExceptionUtil.printStackTrace(e));
          System.exit(-1);
      }
  }
}
